<?php
/**
 * Parses a nodes config field.
 * 
 * @param loaded node
 * @return SimpleXMLElement
 */
function _get_config($node) {
  try {
    $element = new SimpleXMLElement($node->config);
  }
  catch (Exception $e) {
    var_dump($node);
    var_dump($node->config);
    var_dump($e);
  }
  return $element;
}

function _get_boats(SimpleXMLElement $config) {
  $xpath = "//boats/boat";
  $results = $config->xpath($xpath);
  
  if ($results === FALSE || sizeof($results) == 0) {
    error_log("No boats configured.");
  }
  
  return $results;
}

function _get_boat_config_by_id(SimpleXMLElement $config, $boatId) {
  $xpath = "//boat[@id='".$boatId."']";
  $result = $config->xpath($xpath);
  if ($result === FALSE) {
    return FALSE;
  } else if (sizeof($result) == 0) {
    throw new Exception("No boats in config with id $boatId");
  } else if (sizeof($result) > 1) {
    throw new Exception("Multiple boats in config with id $boatId");
  } else {
    return $result[0];
  }
}


function _get_rejection_element(SimpleXMLElement $config) {
  $xpath = "//reject";
  $result = $config->xpath($xpath);
  if ($result === FALSE) {
    return FALSE;
  } else if (sizeof($result) == 0) {
    throw new Exception("No rejection text configured.");
  } else if (sizeof($result) > 1) {
    throw new Exception("Multiple rejection texts in config.");
  } else {
    return $result[0];
  }
}

function _get_clubs(SimpleXMLElement $config) {
  $clubs = array();
  foreach ($config->boats->boat as $boat) {
    $club = (String)$boat['club'];
    if ($club != "" && !in_array($club, $clubs)) {
      $clubs[] = $club;
    }
  }
  return $clubs;
}